﻿using DataModels.Dto;
using DataModels.Dto.Community;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.Community;
using DataModels.Entities.House;
using DataModels.Enums.Community;
using SqlSugar;

namespace Services.Community
{
    public class ButlerEvaluationService(SqlSugarClient db) : BaseService(db)
    {
        /// <summary>
        /// 提交评价
        /// </summary>
        /// <returns></returns>
        public ResponseModel SubmitEvaluation(ButlerEvaluationinfo info)
        {
            // 获取当前年月字符串（格式：YYYY-MM）
            string currentYearMonth = DateTime.Now.ToString("yyyy-MM");

            // 查询当月是否已提交评估
            bool hasSubmitted = db.Queryable<ButlerEvaluation>()
                .Where(be => be.CreateUser == UserUUID)
                .Where(be => be.YearMonth == currentYearMonth)
                .Where(be => be.ProjectUUID == info.ProjectUUID)
                .Where(be => be.HousingBasicUUID == info.HousingBasicUUID)
                .Any();

            // 如果已提交，返回错误响应
            if (hasSubmitted)
            {
                return Error("每月只能提交一次评价");
            }
            int sigeid = GetCustIdBySIGE();
            var data1 = db.Queryable<CustomerHouseRelation, Customer, HousingBasic, Projects, Building, Unit>((chr, c, h, p, bu, unit) => new object[]
            {
                JoinType.Left, chr.CustId == c.CustId,
                JoinType.Left, chr.HouseId == h.HouseId,
                JoinType.Left,chr.OrganId == p.CommunityId,
                JoinType.Left,h.BuildId==bu.BuildId,
                JoinType.Left,h.UnitId==unit.unitId
            })
                .Where(chr => chr.CustId == sigeid)
                .Where(chr => chr.RelType == "1")
                .Select("chr.*, h.UUID as HouseUUId, c.UUID as CustomerUUId,p.ProjectName as ProjectName ,p.UUID as ProjectUUID, bu.UUID as BuildUUID, unit.UUID as unitUUID")
                .First();
            if (data1==null) {
                return Error("房屋不存在");
            }
            // 未提交，则创建新记录
            ButlerEvaluation model = new()
            {
                Performance = (ButlerEvaluationPerformance)info.Performance,
                Comment = info.Comment,
                CreateUser = UserUUID,
                ProjectUUID =info.ProjectUUID,
                HousingBasicUUID=info.HousingBasicUUID,
                StewardUUID =info.StewardUUID
            };

            // 插入新评估记录
            db.Insertable(model).ExecuteCommand();

            return Success(new { data1.BuildUUID });
        }

        /// <summary>
        /// 计算管家满意度统计
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>满意度统计结果</returns>
        public ResponseModel CalculateSatisfaction(DateTime? startDate, DateTime? endDate, string HouseUUID)
        {
            var entity = db.Queryable<HousingBasic>().Where(n => n.UUID.ToString() == HouseUUID).First();
            if (entity == null)
            {
                return Error("房屋不存在");
            }
            var buding = db.Queryable<Building>().Where((n => n.BuildId == entity.BuildId)).First();
            if (buding == null)
            {
                return Error("楼栋不存在");
            }
            var steward = db.Queryable<User>().Where(n => n.BuildIdS.Contains(buding.UUID.ToString())).First();
            if (steward == null)
            {
                return Error("管家不存在");
            }
            string BuildId = buding.UUID.ToString();

            var query = db.Queryable<ButlerEvaluation, User>((b, s) => new object[] { JoinType.Left, s.UUID.ToString() == b.StewardUUID })
                .WhereIF(startDate.HasValue, (s, b) => b.CreateTime >= startDate)
                .WhereIF(endDate.HasValue, (s, b) => b.CreateTime <= endDate)
                .Where((b, s) => s.BuildIdS.Contains(BuildId.ToString()));

            // 计算评价总数
            int totalCount = query.Count();
            var list = query.ToList();

            // 计算满意数量(Performance=1)
            int satisfiedCount = list.Where((b, s) => b.Performance == ButlerEvaluationPerformance.Satisfied)
                                      .Count();

            // 计算中等评价数量(Performance=2)
            int averageCount = list.Where((b, s) => b.Performance == ButlerEvaluationPerformance.Average)
                                    .Count();

            // 计算不满意数量(Performance=3)
            int dissatisfiedCount = list.Where((b, s) => b.Performance == ButlerEvaluationPerformance.Dissatisfied)
                                         .Count();

            // 修改满意度计算方式：(满意数 + 中等评价数) / 总评价数
            decimal satisfactionRate = 0;
            if (totalCount > 0)
            {
                satisfactionRate = Math.Round((decimal)(satisfiedCount + averageCount) / totalCount * 100, 2);
            }

            CalculateSatisfactionResponse res = new()
            {
                UUID = steward.UUID.ToString(),
                Name = steward.DisplayName,
                AvatarUrl = steward.AvatarUrl,
                TotalEvaluations = totalCount,  // 使用总评价数
                SatisfiedCount = satisfiedCount,
                DissatisfiedCount = dissatisfiedCount,
                SatisfactionRate = satisfactionRate
            };
            return Success(res);
        }
    }
}
